<template>
        <n-button type="primary" ghost @click="send" :disabled="time > 0 || !phone" :loading="loading">
            {{ text }}
        </n-button>

</template>

<script setup>
// 引入 naive-ui 组件
import { NButton, createDiscreteApi } from "naive-ui";

// 引入CompositionApi
import { ref, computed } from "vue";

// 声明引用
const props = defineProps({
    phone: {
        type: String,
        default: () => ""
    }
});

// 计时器
const time = ref(0);

// 事件实例
const timer = ref(null);

// 状态
const loading = ref(false);

// 发送验证码事件
const send = async () => {

    loading.value = true;

    const { error, data } = await useGetCaptchaApi(props.phone);

    loading.value = false;

    if (error.value) return;


    if (timer.value) clearInterval(timer.value);

    time.value = 10;

    timer.value = setInterval(() => {
        time.value--;
        if (time.value <= 0) {
            clearInterval(timer.value);
        }
    }, 1000)


    const msg = data.value === "ok" ? `发送成功` : `当前是演示模式,你的验证码:${data.value}`;

    const { message } = createDiscreteApi(["message"]);

    message.success(msg)



};

// 文本
const text = computed(() => {
    if (loading.value) {
        return `发送中...`
    } else if (time.value > 0) {
        return `${time.value} 秒后重新发送`
    } else {
        return `发送验证码`
    };
})


</script>